package routines;
import datastructures.*;
import processors.*;
import java.util.*;

public class RoutineCollection {
	private TreeMap<String, List<Routine>> routineCollection;
	
	public RoutineCollection() {
		routineCollection = new TreeMap<String, List<Routine>>();
	}
	
	/**
	 * Inserts a routine in a routine collection, if there isn't already a 
	 * routine with the same name and with the same set of commands in the
	 * collection.
	 * returns 	true if insert was successful
	 * 			false if a routine with the same set of commands an the same 
	 * 				name is already in the collection
	 */
	public boolean insertRoutine(Routine routine) {
		boolean equal = false;
		List<Routine> l = routineCollection.get(routine.getName());
		if (l == null) {
			routineCollection.put(routine.getName(), 
					l = new ArrayList<Routine>());
		}
		for (Routine each : l) {
			if (each.getUsedCommands().equals(routine.getUsedCommands())) {	
				equal = true;
			}
		}
		if (!equal) {
			l.add(routine);
		}
		return !equal;
	}
	
	/**
	 * Returns the routine with the smallest runtime for a given name
	 * Returns null if the routine does not exist in the routine collection
	 */
	public Routine getRoutine(String name) {
	
		if (!routineCollection.containsKey(name)) {
			return null;
		}
		Routine smallestRuntime = routineCollection.get(name).get(0);
		int runtime = smallestRuntime.getRuntime();
		for (Routine each : routineCollection.get(name)) {
			if (runtime < each.getRuntime()) {
				smallestRuntime = each;
				runtime = each.getRuntime();
			}
		}
		return smallestRuntime;
	}
}
